package kokonut.shop.cart;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kokonut.shop.color.ExistingColors;
import kokonut.shop.product.TShirt;
import kokonut.shop.product.TShirtModel;
import kokonut.shop.size.ExistingSizes;

import persistence.ProductPersistence;

public class AddToCartServlet extends HttpServlet {
    @Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
              throws IOException {

    	int ref = Integer.parseInt(req.getParameter("ref"));
    	int amount = Integer.parseInt(req.getParameter("amount"));
    	ProductPersistence persistence = new ProductPersistence();
    	TShirtModel model = (TShirtModel)persistence.loadModelByRef(ref);
    	TShirt shirt = new TShirt(ref, model.getName(), null, null, model.getModelImages());
    	ExistingColors color = loadSelectedColor(req.getParameter("colors"));
    	shirt.setColor(color);
    	String sizeStr = req.getParameter("sizes");
    	ExistingSizes size = loadSelectedSize(sizeStr);
    	shirt.setSize(size);
    	shirt.setPrice(model.getPriceBySize(sizeStr));
    	CartController cartController = new CartController();
    	if(cartController.productAlreadyInCart(shirt))
    		cartController.updateProductInCart(shirt,amount);
    	else
    		cartController.addProductToCart(shirt,amount);
    	resp.sendRedirect("/shop");
    }

    private ExistingSizes loadSelectedSize(String str) {
		if(str.equals("S"))
			return ExistingSizes.S;
		if(str.equals("M"))
			return ExistingSizes.M;
		if(str.equals("L"))
			return ExistingSizes.L;
		if(str.equals("XL"))
			return ExistingSizes.XL;
		if(str.equals("XXL"))
			return ExistingSizes.XXL;
		return null;
	}

	private ExistingColors loadSelectedColor(String str) {
		if(str.equals("BLACK"))
			return ExistingColors.BLACK;
		if(str.equals("BLUE"))
			return ExistingColors.BLUE;
		if(str.equals("BROWN"))
			return ExistingColors.BROWN;
		if(str.equals("GREEN"))
			return ExistingColors.GREEN;
		if(str.equals("GREY"))
			return ExistingColors.GREY;
		if(str.equals("ORANGE"))
			return ExistingColors.ORANGE;
		if(str.equals("PINK"))
			return ExistingColors.PINK;
		if(str.equals("PURPLE"))
			return ExistingColors.PURPLE;
		if(str.equals("RED"))
			return ExistingColors.RED;
		if(str.equals("WHITE"))
			return ExistingColors.WHITE;
		if(str.equals("YELLOW"))
			return ExistingColors.YELLOW;
		return null;
	}
}